<template>
  <view class="login-container">
    <!-- 顶部背景 -->
    <view class="login-background"></view>

    <!-- 登录卡片 -->
    <view class="login-card">
      <view class="login-title">渠道登录</view>

      <!-- 登录方式切换 -->
      <view class="login-tabs">
        <view
          class="login-tab"
          :class="{ active: loginType === 'password' }"
          @click="loginType = 'password'"
        >
          账号密码登录
        </view>
        <view
          class="login-tab"
          :class="{ active: loginType === 'code' }"
          @click="loginType = 'code'"
        >
          验证码登录
        </view>
      </view>

      <!-- 登录表单 -->
      <view class="login-form">
        <!-- 手机号输入 -->
        <view class="form-item">
          <text class="iconfont icon-shouji"></text>
          <input
            type="number"
            v-model="formData.mobile"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </view>

        <!-- 密码登录表单 -->
        <block v-if="loginType === 'password'">
          <view class="form-item">
            <text class="iconfont icon-mima"></text>
            <input
              v-if="showPassword"
              type="text"
              v-model="formData.password"
              placeholder="请输入密码"
              maxlength="20"
            />
            <input
              v-if="!showPassword"
              type="password"
              v-model="formData.password"
              placeholder="请输入密码"
              maxlength="20"
              :password="true"
            />
            <text
              class="iconfont"
              :class="showPassword ? 'icon-xianshimima' : 'icon-buxianshimima'"
              @click="passwordEyeClick"
              style="padding: 0 0 0 20px"
            ></text>
          </view>
        </block>

        <!-- 验证码登录表单 -->
        <block v-else>
          <!-- 图形验证码 -->
          <view class="form-item">
            <text class="iconfont icon-yanzhengma"></text>
            <input
              type="text"
              v-model="formData.img_code"
              placeholder="请输入图形码"
              maxlength="4"
            />
            <image
              class="img-code"
              :src="imgCodeUrl"
              @click="refreshImgCode"
              mode="aspectFit"
            ></image>
          </view>

          <!-- 短信验证码 -->
          <view class="form-item">
            <text class="iconfont icon-yanzhengma"></text>
            <input
              type="number"
              v-model="formData.verify_code"
              placeholder="请输入短信验证码"
              maxlength="6"
            />
            <view
              class="verify-code-btn"
              :class="{ disabled: countDown > 0 || isSendingCode }"
              @click="getVerifyCode"
            >
              <text v-if="isSendingCode" class="loading-icon"></text>
              <text v-else>{{ countDown > 0 ? `${countDown}s` : "获取验证码" }}</text>
            </view>
          </view>
        </block>
      </view>

      <!-- 登录按钮 -->
      <view class="login-btn" :class="{ loading: isLoggingIn }" @click="handleLogin">
        <text v-if="!isLoggingIn">登录</text>
        <text v-else class="loading-spinner"></text>
      </view>

      <!-- 底部链接 -->
      <view class="login-links">
        <text @click="goToRegister">注册账号</text>
        <text @click="goToForget">忘记密码?</text>
      </view>
    </view>

    <!-- 底部提示文本 -->
    <view class="login-footer">沃客薪服 · 渠道服务平台</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loginType: "password", // 登录方式: password-密码登录, code-验证码登录
      showPassword: false, // 是否显示密码
      formData: {
        mobile: "", // 手机号
        password: "", // 密码
        img_code: "", // 图形验证码
        img_key: "", // 图形验证码key
        verify_code: "", // 短信验证码
      },
      imgCodeUrl: "", // 图形验证码图片
      countDown: 0, // 验证码倒计时
      timer: null, // 定时器
      isSendingCode: false, // 发送验证码状态
      isLoggingIn: false, // 登录状态
    };
  },
  onLoad(e) {
    // 扫码进入本小程序,快速绑定企业
    if (e.scene) {
      let scene = decodeURIComponent(e.scene);
      let code_keyword =
        scene && scene.indexOf("=") != -1 && scene.split("=").length >= 2
          ? scene.split("=")[1]
          : "";
      if (code_keyword) {
        // 设置邀请状态:待邀请
        uni.setStorageSync("inviteComp", {
          keyword: code_keyword,
          invited: false, // 待邀请
        });
      }
    }

    // 检查是否已登录
    const token = uni.getStorageSync("token");
    if (token) {
      uni.reLaunch({
        url: "/pages/index",
      });
      return;
    }

    // 加载图形验证码
    this.refreshImgCode();
  },
  onShow() {
    // 如果选中验证码登录，并且图形验证码为空，刷新图形验证码
    if (this.loginType === "code" && !this.imgCodeUrl) {
      this.refreshImgCode();
    }
  },
  onUnload() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  methods: {
    // 刷新图形验证码
    refreshImgCode() {
      // 生成随机key
      this.formData.img_key = Date.now() + Math.random().toString(36).substr(2, 10);

      // 发送POST请求获取base64图片
      this.$request.getImgCode(
        {
          key: this.formData.img_key,
          type: "base64",
        },
        (res) => {
          console.log("验证码返回:", res);

          // 正确处理嵌套的数据结构
          if (res.data) {
            // 注意这里是 res.data.image，因为响应中有嵌套的data字段
            this.imgCodeUrl = res.data.image;
            // console.log("设置图片URL:", this.imgCodeUrl);
          } else {
            console.error("获取验证码失败，返回数据结构不符合预期:", res);
            uni.showToast({
              title: "获取验证码失败",
              icon: "none",
            });
          }
        },
        (err) => {
          console.error("请求验证码失败:", err);
          uni.showToast({
            title: "网络错误，获取验证码失败",
            icon: "none",
          });
        }
      );
    },

    // 获取短信验证码
    getVerifyCode() {
      if (!/^1[3-9]\d{9}$/.test(this.formData.mobile)) {
        uni.showToast({
          title: "请输入有效的手机号",
          icon: "none",
          mask: true,
          duration: 1500,
        });
        return;
      }
      if (this.formData.img_code.trim().length != 4) {
        uni.showToast({
          title: "请输入4位数的图形码",
          icon: "none",
          mask: true,
          duration: 1500,
        });
        return;
      }

      // 倒计时中或正在发送时不能重复获取
      if (this.countDown > 0 || this.isSendingCode) {
        return;
      }

      // 验证手机号
      if (!this.formData.mobile) {
        uni.showToast({
          title: "请输入手机号",
          icon: "none",
        });
        return;
      }

      if (!/^1\d{10}$/.test(this.formData.mobile)) {
        uni.showToast({
          title: "手机号格式不正确",
          icon: "none",
        });
        return;
      }

      // 验证图形验证码
      if (!this.formData.img_code) {
        uni.showToast({
          title: "请输入图形验证码",
          icon: "none",
        });
        return;
      }

      // 设置发送状态
      this.isSendingCode = true;

      // 发送请求
      this.$request.getSmsCode(
        {
          mobile: this.formData.mobile,
          scenario: "2", // 1员工注册登录 2渠道注册登录 3发薪确认 4变更员工手机号 5变更渠道手机号 6渠道忘记密码
        },
        (res) => {
          // this.formData.smsToken = res.sms_token;

          // 提示成功
          uni.showToast({
            title: "验证码已发送",
            icon: "success",
          });

          // 开始倒计时
          this.startCountdown();
        },
        () => {
          uni.showToast({
            title: "网络异常，请稍后重试",
            icon: "none",
          });
        },
        () => {
          // 重置发送状态
          this.isSendingCode = false;
        }
      );
    },

    // 开始倒计时
    startCountdown() {
      this.countDown = 60;

      // 清除可能存在的定时器
      if (this.timer) {
        clearInterval(this.timer);
      }

      this.timer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown--;
        } else {
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    },

    // 登录
    handleLogin() {
      // 防止重复点击
      if (this.isLoggingIn) {
        return;
      }

      // 验证手机号
      if (!this.formData.mobile) {
        uni.showToast({
          title: "请输入手机号",
          icon: "none",
        });
        return;
      }

      if (!/^1\d{10}$/.test(this.formData.mobile)) {
        uni.showToast({
          title: "手机号格式不正确",
          icon: "none",
        });
        return;
      }

      // 根据登录方式验证参数
      if (this.loginType === "password") {
        // 密码登录
        if (!this.formData.password) {
          uni.showToast({
            title: "请输入密码",
            icon: "none",
          });
          return;
        }

        if (this.formData.password.length < 6) {
          uni.showToast({
            title: "密码不能少于6位",
            icon: "none",
          });
          return;
        }
      } else {
        // 验证码登录
        if (!this.formData.img_code) {
          uni.showToast({
            title: "请输入图形验证码",
            icon: "none",
          });
          return;
        }

        if (!this.formData.verify_code) {
          uni.showToast({
            title: "请输入短信验证码",
            icon: "none",
          });
          return;
        }

        if (this.formData.verify_code.length !== 6) {
          uni.showToast({
            title: "验证码格式不正确",
            icon: "none",
          });
          return;
        }
      }

      // 设置登录状态
      this.isLoggingIn = true;

      // 准备请求数据
      const params = {
        mobile: this.formData.mobile,
      };

      // 根据登录方式设置参数
      if (this.loginType === "password") {
        params.password = this.formData.password;
      } else {
        params.verify_code = this.formData.verify_code;
      }

      // 发送登录请求
      this.$request.login(
        params,
        (res) => {
          // 保存登录信息
          uni.setStorageSync("token", res.token);
          uni.setStorageSync("channelInfo", {
            id: res.channel_id,
            name: res.name,
            mobile: res.mobile,
          });

          // 提示登录成功
          uni.showToast({
            title: "登录成功",
            icon: "success",
          });

          // 跳转到首页
          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/index",
            });
          }, 1500);
        },
        (err) => {
          // 登录失败，刷新图形验证码
          if (this.loginType === "code") {
            this.refreshImgCode();
          }
        },
        () => {
          // 重置登录状态
          this.isLoggingIn = false;
        }
      );
    },

    // 跳转到注册页面
    goToRegister() {
      uni.navigateTo({
        url: "/pages/register",
      });
    },

    // 跳转到忘记密码页面
    goToForget() {
      uni.navigateTo({
        url: "/pages/forget",
      });
    },
    passwordEyeClick() {
      this.showPassword = !this.showPassword;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/static/scss/variables.scss";
.login-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f5f5f5;
  position: relative;

  /* 顶部背景 */
  .login-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 400rpx;
    background: linear-gradient(to bottom, $colorPrimary, $colorPrimaryLight);
    border-radius: 0 0 50% 50% / 0 0 20% 20%;
    z-index: 1;
  }

  /* 登录卡片 */
  .login-card {
    position: relative;
    width: 90%;
    margin-top: 180rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 30rpx rgba(0, 0, 0, 0.1);
    padding: 60rpx 40rpx;
    z-index: 2;

    .login-title {
      font-size: 48rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
      margin-bottom: 60rpx;
    }

    /* 标签页 */
    .login-tabs {
      display: flex;
      justify-content: space-around;
      margin-bottom: 40rpx;

      .login-tab {
        font-size: 28rpx;
        color: #999;
        padding: 20rpx 0;
        position: relative;

        &.active {
          color: $colorPrimary;
          font-weight: bold;

          &:after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60rpx;
            height: 6rpx;
            background-color: $colorPrimary;
            border-radius: 3rpx;
          }
        }
      }
    }

    /* 表单样式 */
    .login-form {
      margin-bottom: 60rpx;

      .form-item {
        display: flex;
        align-items: center;
        height: 110rpx;
        border-bottom: 1rpx solid #eee;
        margin-bottom: 30rpx;

        .iconfont {
          font-size: 40rpx;
          color: $colorPrimary;
          margin-right: 20rpx;
        }

        input {
          flex: 1;
          height: 100%;
          font-size: 28rpx;
        }

        .img-code {
          width: 300rpx;
          height: 100rpx;
          background-color: #f5f5f5;
          border-radius: 8rpx;
        }

        .verify-code-btn {
          width: 220rpx;
          height: 70rpx;
          line-height: 70rpx;
          text-align: center;
          color: #fff;
          font-size: 24rpx;
          background-color: $colorPrimary;
          border-radius: 35rpx;
          display: flex;
          justify-content: center;
          align-items: center;

          .loading-icon {
            display: inline-block;
            width: 30rpx;
            height: 30rpx;
            border: 2rpx solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 0.8s linear infinite;
          }

          &.disabled {
            background-color: #ccc;
          }
        }
      }
    }

    /* 登录按钮 */
    .login-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      text-align: center;
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
      background-color: $colorPrimary;
      border-radius: 45rpx;
      margin-bottom: 40rpx;
      display: flex;
      justify-content: center;
      align-items: center;

      &.loading {
        opacity: 0.85;
      }

      .loading-spinner {
        display: inline-block;
        width: 30rpx;
        height: 30rpx;
        border: 3rpx solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        border-top-color: #fff;
        animation: spin 0.8s linear infinite;
      }
    }

    /* 底部链接 */
    .login-links {
      display: flex;
      justify-content: space-between;
      font-size: 26rpx;
      color: #666;

      text {
        padding: 10rpx;
      }
    }
  }

  /* 底部文本 */
  .login-footer {
    position: fixed;
    bottom: 60rpx;
    font-size: 24rpx;
    color: #999;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
